package com.piece.core.db.initializer;

import com.piece.core.db.util.SchemaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Comparator;
import java.util.List;

/**
 * 数据脚本初始化
 */
@Slf4j
public class DataSourceInitializer {

    private DataSource dataSource;
    private List<DataSourceScript> dataSourceScript;

    public DataSourceInitializer(DataSource dataSource, List<DataSourceScript> dataSourceScript) {
        log.info("加载 DataSourceInitializer ...");
        this.dataSource = dataSource;
        this.dataSourceScript = dataSourceScript;
    }

    public void runScript() {
        if (CollectionUtils.isNotEmpty(dataSourceScript)) {
            dataSourceScript.sort(Comparator.comparing(DataSourceScript::getIndex));

            dataSourceScript.forEach(script -> {
                try {
                    List<InputStream> streams = script.loadScript();
                    if (CollectionUtils.isNotEmpty(streams)) {
                        log.info("加载 DataSourceInitializer --> {}", script.getScriptName());
                        SchemaUtil.initSchema(streams, dataSource);
                    }
                } catch (Exception e) {
                    log.error("数据脚本[{}]初始化失败{}", script.getClass().getSimpleName(), e);
                }
            });
        }
    }
}
